package com.clickpaas.workinghours.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

@Api(description = "文件上传下载")
@RestController
@RequestMapping(value = "/file")
@Slf4j
public class UploadController {

    @ApiOperation("上传文件")
    @RequestMapping(value="/uploadWbs",method=RequestMethod.POST)
    @ResponseBody
    public String uploadFile(@RequestParam("uploadFile")MultipartFile uploadFile, HttpServletRequest request) {
        try{
            //创建文件在服务器端的存放路径
            //String dir=request.getServletContext().getRealPath("/Users/edz/Nextcloud/mac/project/java/clickpaas-springcloud/filePath");
            String dir = "/Users/edz/Nextcloud/mac/project/java/clickpaas-springcloud/filePath";
            File fileDir = new File(dir);
            if(!fileDir.exists())
                fileDir.mkdirs();
            //生成文件在服务器端存放的名字
            String originalFilename = uploadFile.getOriginalFilename();
            StringBuffer stringBuffer = new StringBuffer(originalFilename);
            //时间格式化格式
            SimpleDateFormat simpleDateFormat =new SimpleDateFormat("_yyyyMMddHHmmssSSS");
            //获取当前时间并作为时间戳
            String timeStamp=simpleDateFormat.format(new Date());
            //拼接新的文件名
            stringBuffer.insert(originalFilename.indexOf("."),timeStamp);
            File files = new File(fileDir+"/"+stringBuffer);
            //上传
            uploadFile.transferTo(files);
        }catch(Exception e) {
            e.printStackTrace();
            return "上传失败";
        }
        return "上传成功";
    }

    @ApiOperation("下载文件")
    @RequestMapping(value="/downloadWbs",method=RequestMethod.GET)
    @ResponseBody
    public String downloadFile(@RequestParam("downloadFileName") String downloadFileName,HttpServletRequest request,HttpServletResponse response) {
        String downloadFilePath = "/Users/edz/Nextcloud/mac/project/java/clickpaas-springcloud/filePath";
        File file = new File(downloadFilePath +'/'+ downloadFileName);
        if(!file.exists()){
            return "下载文件不存在";
        }
        //浏览器设置
        String userAgent = request.getHeader("User-Agent");
        try {
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                //IE浏览器处理
                downloadFileName = java.net.URLEncoder.encode(downloadFileName, "UTF-8");
            } else {
                // 非IE浏览器的处理：
                downloadFileName = new String(downloadFileName.getBytes("UTF-8"), "ISO-8859-1");
            }
        } catch (UnsupportedEncodingException e) {
            log.info("下载文件异常【{}】",e);
        }
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + downloadFileName );
        OutputStream os = null;
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            byte[] buff = new byte[1024];
            os  = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (Exception e) {
            log.info("下载文件异常【{}】",e);
            return "下载失败";
        }finally {
            try {
                if (null != os){
                    os.close();
                }
                if (null != bis){
                    bis.close();
                }
            } catch (IOException e) {
                log.info("文件输出流关闭失败：【{}】",e);
            }
        }
        return "下载成功";
    }
}
